import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { User } from '../login-data/user';
import 'rxjs/add/operator/map';
import { Storage } from '@ionic/storage';


@Injectable()
export class UserSettingProvider {
  private readonly baseUrl: string = 'https://api.bmob.cn/1';
  private readonly httpHeaders : Object = {
    headers : new HttpHeaders({
      'X-Bmob-Application-Id':'748054e798358354bf419b92c0dd9638',
      'X-Bmob-REST-API-Key':'452b75414d0a4920470d5ff482cb451d',
      'Content-Type':'application/json'
    }) 
  }
  HttpHeaders = new HttpHeaders(
    {
      
    }
  );

  constructor(public http: HttpClient,

    private storage: Storage) {
    console.log('获取Http数据服务加载');
  }

  /**
   * 获取用户数据
   * @returns {Observable<User[]>}  用户数据集合
   */
  getUsers(): Observable<User[]>{
    return this.http.get<User[]>(`${this.baseUrl}/classes/_User`,this.httpHeaders)
    .map(data => data["results"]);
  }
  /**
   * 
   * @param objectid 查询单条数据
   */
  // getUserDetail(objectid:string):Observable<User>{
  //   return this.http.get<User>("${this.baseUrl}/classes/user/${objectId}",
  //   {headers:this.httpHeaders});
  // }


   /**
   * 删除指定用户
   * @param user
   * @returns {Observable<User>}   响应结果
   */
  deleteUser(user : User):Observable<{}>{
    return this.http.delete(`${this.baseUrl}/classes/_User/${user.objectId}`,
    this.httpHeaders);
  }

  /**
   * 设置最后更新时间
   */
  setRefreshData():Promise<any>{
    return this.storage.set('updateTime',Date.now());
  }

  /**
   * 更新指定用户
   *  @param task
   * @returns {Observable<Task>} 响应结果
   * */
  updateUser(user : User): Observable<User>{
    let _user = {username:user.username, mobilePhoneNumber: user.mobilePhoneNumber,
      belong:user.belong,position:user.position};
    return this.http.put<User>(`${this.baseUrl}/classes/_User/${user.objectId}`,
    _user,this.httpHeaders);
  }
  /**
   * 缓存是否需要更新
   * 间隔时间：24*60*60
   */
  isRefreshData():Promise<boolean>{
    return this.storage.get('updateTime')
      .then(value=>{
        console.log(value);
        console.log(Date.now());
        
        return (Date.now()-value)/1000>24*60*60?true:false;
      });
  }

}
